package com.tao.plan.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.tao.plan.domain.dto.LoginDto;
import com.tao.plan.domain.pojo.PUser;
import com.tao.plan.mapper.PUserMapper;
import com.tao.plan.service.PUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tao.plan.common.prop.WxAppProperties;
import org.apache.ibatis.logging.LogException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class PUserServiceImpl extends ServiceImpl<PUserMapper, PUser> implements PUserService {
	@Autowired
	private WxAppProperties wxAppProperties;
	@Override
	public PUser wxLogin(LoginDto loginDto) {
		// 目标 URL
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		// 使用 HttpRequest 构建 GET 请求
		HttpResponse response = HttpRequest.get(url)
				.header("Accept", "application/json") // 添加请求头
				.form("appid", wxAppProperties.getAppid()) // 添加表单参数
				.form("secret", wxAppProperties.getSecret()) // 添加表单参数
				.form("js_code", loginDto.getCode()) // 添加表单参数
				.form("js_code", "authorization_code") // 添加表单参数
				.execute();
		// 获取响应状态码和响应体
		int status = response.getStatus();
		String body = response.body();
		Map<String,String> map = JSONUtil.toBean(body, Map.class);
		// 获取 openid
		String openid = map.get("openid");
		if (openid == null){
			throw new LogException("登录失败, 获取的openid不正确");
		}
		PUser pUser = new PUser();
		pUser.setOpenid(openid);
		return pUser;
	}
	// 这里可以实现自定义的方法
}
